<?php

function kq_ck_null($kq_va,$kq_na) {
    if($kq_va == "") {
      $kq_va="";
    } else {
      return $kq_va=$kq_na.'='.$kq_va.'&';
    }
}

class ControllerPaymentKuaiqianb2b extends Controller {

  const merchantAcctId = '1007883177601';

  function test() {
    $ss = $this->buildReqest(1987, 19872639872938, 'http://www.bing.com');
    echo $ss;
  }

  public function buildReqest($amount, $orderId, $bgUrl) {
    //人民币网关账号，该账号为11位人民币网关商户编号+01,该参数必填。
    $merchantAcctId = ControllerPaymentKuaiqianb2b::merchantAcctId;
    //编码方式，1代表 UTF-8; 2 代表 GBK; 3代表 GB2312 默认为1,该参数必填。
    $inputCharset = "1";
    //接收支付结果的页面地址，该参数一般置为空即可。
    $pageUrl = "";
    //服务器接收支付结果的后台地址，该参数务必填写，不能为空。
    $bgUrl = $bgUrl;
    //网关版本，固定值：v2.0,该参数必填。
    $version =  "v2.0";
    //语言种类，1代表中文显示，2代表英文显示。默认为1,该参数必填。
    $language =  "1";
    //签名类型,该值为4，代表PKI加密方式,该参数必填。
    $signType =  "4";
    //支付人姓名,可以为空。
    $payerName= ""; 
    //支付人联系类型，1 代表电子邮件方式；2 代表手机联系方式。可以为空。
    $payerContactType =  "1";
    //支付人联系方式，与payerContactType设置对应，payerContactType为1，则填写邮箱地址；payerContactType为2，则填写手机号码。可以为空。
    $payerContact =  "";
    //商户订单号，以下采用时间来定义订单号，商户可以根据自己订单号的定义规则来定义该值，不能为空。
    $orderId = $orderId;
    //订单金额，金额以“分”为单位，商户测试以1分测试即可，切勿以大金额测试。该参数必填。
    $amount2 = (float)$amount;
    $amount2 = number_format($amount2*100,0,'.','');
    $orderAmount = $amount2;
    //订单提交时间，格式：yyyyMMddHHmmss，如：20071117020101，不能为空。
    $orderTime = date("YmdHis");
    //商品名称，可以为空。
    $productName= ""; 
    //商品数量，可以为空。
    $productNum = "";
    //商品代码，可以为空。
    $productId = "";
    //商品描述，可以为空。
    $productDesc = "";
    //扩展字段1，商户可以传递自己需要的参数，支付完快钱会原值返回，可以为空。
    $ext1 = "";
    //扩展自段2，商户可以传递自己需要的参数，支付完快钱会原值返回，可以为空。
    $ext2 = "";
    //支付方式，一般为00，代表所有的支付方式。如果是银行直连商户，该值为10，必填。
    $payType = "00";
    //银行代码，如果payType为00，该值可以为空；如果payType为10，该值必须填写，具体请参考银行列表。
    $bankId = "";
    //同一订单禁止重复提交标志，实物购物车填1，虚拟产品用0。1代表只能提交一次，0代表在支付不成功情况下可以再提交。可为空。
    $redoFlag = "";
    //快钱合作伙伴的帐户号，即商户编号，可为空。
    $pid = "";

    $kq_all_para=kq_ck_null($inputCharset,'inputCharset');
    $kq_all_para.=kq_ck_null($pageUrl,"pageUrl");
    $kq_all_para.=kq_ck_null($bgUrl,'bgUrl');
    $kq_all_para.=kq_ck_null($version,'version');
    $kq_all_para.=kq_ck_null($language,'language');
    $kq_all_para.=kq_ck_null($signType,'signType');
    $kq_all_para.=kq_ck_null($merchantAcctId,'merchantAcctId');
    $kq_all_para.=kq_ck_null($payerName,'payerName');
    $kq_all_para.=kq_ck_null($payerContactType,'payerContactType');
    $kq_all_para.=kq_ck_null($payerContact,'payerContact');
    $kq_all_para.=kq_ck_null($orderId,'orderId');
    $kq_all_para.=kq_ck_null($orderAmount,'orderAmount');
    $kq_all_para.=kq_ck_null($orderTime,'orderTime');
    $kq_all_para.=kq_ck_null($productName,'productName');
    $kq_all_para.=kq_ck_null($productNum,'productNum');
    $kq_all_para.=kq_ck_null($productId,'productId');
    $kq_all_para.=kq_ck_null($productDesc,'productDesc');
    $kq_all_para.=kq_ck_null($ext1,'ext1');
    $kq_all_para.=kq_ck_null($ext2,'ext2');
    $kq_all_para.=kq_ck_null($payType,'payType');
    $kq_all_para.=kq_ck_null($bankId,'bankId');
    $kq_all_para.=kq_ck_null($redoFlag,'redoFlag');
    $kq_all_para.=kq_ck_null($pid,'pid');
    
    $kq_all_para=substr($kq_all_para,0,strlen($kq_all_para)-1);

    /////////////  RSA 签名计算 ///////// 开始 //
    $fp = fopen(DIR_SYSTEM . "library/cert/99bill-rsa.pem", "r"); 
    $priv_key = fread($fp, 123456);
    fclose($fp);
    $pkeyid = openssl_get_privatekey($priv_key);

    // compute signature
    openssl_sign($kq_all_para, $signMsg, $pkeyid,OPENSSL_ALGO_SHA1);

    // free the key from memory
    openssl_free_key($pkeyid);

    $signMsg = base64_encode($signMsg);

    $sHtml = '<form id="kqPay" name="kqPay" action="https://www.99bill.com/gateway/recvMerchantInfoAction.htm" method="post">
        <input type="hidden" name="inputCharset" value="'. $inputCharset . '"/>
        <input type="hidden" name="pageUrl" value="'. $pageUrl . '"/>
        <input type="hidden" name="bgUrl" value="'. $bgUrl . '"/>
        <input type="hidden" name="version" value="'. $version . '"/>
        <input type="hidden" name="language" value="'. $language . '"/>
        <input type="hidden" name="signType" value="'. $signType . '"/>
        <input type="hidden" name="signMsg" value="'. $signMsg . '"/>
        <input type="hidden" name="merchantAcctId" value="'. $merchantAcctId . '"/>
        <input type="hidden" name="payerName" value="'. $payerName . '"/>
        <input type="hidden" name="payerContactType" value="'. $payerContactType . '"/>
        <input type="hidden" name="payerContact" value="'. $payerContact . '"/>
        <input type="hidden" name="orderId" value="'. $orderId . '"/>
        <input type="hidden" name="orderAmount" value="'. $orderAmount . '"/>
        <input type="hidden" name="orderTime" value="'. $orderTime . '"/>
        <input type="hidden" name="productName" value="'. $productName . '"/>
        <input type="hidden" name="productNum" value="'. $productNum . '"/>
        <input type="hidden" name="productId" value="'. $productId . '"/>
        <input type="hidden" name="productDesc" value="'. $productDesc . '"/>
        <input type="hidden" name="ext1" value="'. $ext1 . '"/>
        <input type="hidden" name="ext2" value="'. $ext2 . '"/>
        <input type="hidden" name="payType" value="'. $payType . '"/>
        <input type="hidden" name="bankId" value="'. $bankId . '"/>
        <input type="hidden" name="redoFlag" value="'. $redoFlag . '"/>
        <input type="hidden" name="pid" value="'. $pid . '"/>
        <input style="display:none;" type="submit" value="提交到快钱">
      </form>';
    
    $sHtml = $sHtml."<script>document.forms['kqPay'].submit();</script>";
    
    return $sHtml;
  }

  public function index() {
    $this->load->model('checkout/order');

    $order_id = $this->session->data['order_id'];

    $order_info = $this->model_checkout_order->getOrder($order_id);
    
    $this->load->model('account/order');

    $shipping_cost = 0;

    $totals = $this->model_account_order->getOrderTotals($order_id);

    foreach ($totals as $total) {
      
      if($total['title'] == 'shipping') {
        
        $shipping_cost = $total['value'];
        
      }
      
    }
    

        $payment_type = "1";

        $notify_url = HTTPS_SERVER.'catalog/controller/payment/kuaiqianb2b_callback.php';

        // $return_url = $this->url->link('common/pc') . '#/payment/return';

        $seller_email = $this->config->get('kuaiqianb2b_seller_email');

        $out_trade_no = $this->session->data['order_id'];

        $subject = $item_name . ' ' . $this->language->get('text_order') .' '. $order_id;

        $amount = $order_info['total'];
    
    $currency_value = $this->currency->getValue('CNY');
    $price = $amount * $currency_value;
    $price = number_format($price,2,'.','');
    
    $total_fee = $price;

    $data['html_text'] = $this->buildReqest($total_fee, $order_id, $notify_url);
    
    if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/kuaiqianb2b.tpl')) {
      return $this->load->view($this->config->get('config_template') . '/template/payment/kuaiqianb2b.tpl', $data);
    } else {
      return $this->load->view('default/template/payment/kuaiqianb2b.tpl', $data);
    }
    
  }
  
  public function callback() {
    $kq_check_all_para=kq_ck_null($_REQUEST['merchantAcctId'],'merchantAcctId');
    $kq_check_all_para.=kq_ck_null($_REQUEST['version'],'version');
    $kq_check_all_para.=kq_ck_null($_REQUEST['language'],'language');
    $kq_check_all_para.=kq_ck_null($_REQUEST['signType'],'signType');
    $kq_check_all_para.=kq_ck_null($_REQUEST['payType'],'payType');
    $kq_check_all_para.=kq_ck_null($_REQUEST['bankId'],'bankId');
    $kq_check_all_para.=kq_ck_null($_REQUEST['orderId'],'orderId');
    $kq_check_all_para.=kq_ck_null($_REQUEST['orderTime'],'orderTime');
    $kq_check_all_para.=kq_ck_null($_REQUEST['orderAmount'],'orderAmount');
    $kq_check_all_para.=kq_ck_null($_REQUEST['dealId'],'dealId');
    $kq_check_all_para.=kq_ck_null($_REQUEST['bankDealId'],'bankDealId');
    $kq_check_all_para.=kq_ck_null($_REQUEST['dealTime'],'dealTime');
    $kq_check_all_para.=kq_ck_null($_REQUEST['payAmount'],'payAmount');
    $kq_check_all_para.=kq_ck_null($_REQUEST['fee'],'fee');
    $kq_check_all_para.=kq_ck_null($_REQUEST['ext1'],'ext1');
    $kq_check_all_para.=kq_ck_null($_REQUEST['ext2'],'ext2');
    $kq_check_all_para.=kq_ck_null($_REQUEST['payResult'],'payResult');
    $kq_check_all_para.=kq_ck_null($_REQUEST['errCode'],'errCode');

    $trans_body=substr($kq_check_all_para,0,strlen($kq_check_all_para)-1);
    $MAC=base64_decode($_REQUEST['signMsg']);

    $fp = fopen(DIR_SYSTEM . "library/cert/99bill.cert.rsa.20340630.cer", "r"); 
    $cert = fread($fp, 8192); 
    fclose($fp); 
    $pubkeyid = openssl_get_publickey($cert); 
    $verify_result = openssl_verify($trans_body, $MAC, $pubkeyid); 

    $log = false;

    if($log) {
      $this->log->write('Kuaiqian_B2B :: Two: ' . $verify_result);
    }
    
    if($verify_result) {
          
      $out_trade_no = $_REQUEST['orderId'];
      
      $order_id   = $out_trade_no; 
      
      $order_status_id = $this->config->get('config_order_status_id');
      
      $this->load->model('checkout/order');

      $order_info = $this->model_checkout_order->getOrder($order_id);
      
      if($log) {
        $this->log->write('Kuaiqian_B2B :: Three: ');
      }
      
      if ($order_info) {
        
        if($log) {
          $this->log->write('Kuaiqian_B2B :: Four: ');
        }
        
      
        if($_REQUEST['payResult']=='10') {
        
          if($log) {
            $this->log->write('Kuaiqian_B2B :: Five: ');
          }

          $rtnUrl = $this->url->link('checkout/success');
          // $rtnUrl = $this->url->link('common/pc') . '#/payment/return?';
          $success_rtn = '<result>1</result> <redirecturl>'.$rtnUrl.'</redirecturl>';
        
          $order_status_id = $this->config->get('kuaiqianb2b_order_status_id');
          $this->model_checkout_order->setIsPay($order_id);
          // 修改应付
          $res = $this->model_checkout_order->getOrderById($order_id);
          if ($res) {
            $this->model_checkout_order->updatemoney($res,$order_id) ;
          }                          
         
          if (!$order_info['order_status_id']) {
            
            $this->model_checkout_order->addOrderHistory($order_id, $order_status_id, '', true);
            
          } else {
            
            $this->model_checkout_order->addOrderHistory($order_id, $order_status_id, '', true);
            
          }
        
            
          echo $success_rtn; 
      
        }
        
        //清除sesssion，避免客户返回不到成功页面而无法清除原有的购物车等信息
        $this->cart->clear();
        unset($this->session->data['shipping_method']);
        unset($this->session->data['shipping_methods']);
        unset($this->session->data['payment_method']);
        unset($this->session->data['payment_methods']);
        unset($this->session->data['guest']);
        unset($this->session->data['comment']);
        unset($this->session->data['order_id']);
        unset($this->session->data['coupon']);
        unset($this->session->data['reward']);
        unset($this->session->data['voucher']);
        unset($this->session->data['vouchers']);
        unset($this->session->data['totals']);
        
      }else{
        
        if($log) {
          $this->log->write('Kuaiqian_B2B :: Seven: ');
        }
        
        echo "fail";
        
      }
      
    } else {
      
      if($log) {
        $this->log->write('Kuaiqian_B2B :: Eight: ');
      }
      
      echo "fail";
    
    }    
  }
}